package com.alibaba.travel.article.service.impl;

import com.alibaba.travel.article.dao.UserArticleHistoryDao;
import com.alibaba.travel.article.entity.UserArticleHistoryEntity;
import com.alibaba.travel.article.interceptor.LoginInterceptor;
import com.alibaba.travel.article.service.UserArticleHistoryService;
import com.alibaba.travel.common.utils.Constant;
import com.alibaba.travel.common.utils.PageUtils;
import com.alibaba.travel.common.utils.Query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("userArticleHistoryService")
public class UserArticleHistoryServiceImpl extends ServiceImpl<UserArticleHistoryDao, UserArticleHistoryEntity> implements UserArticleHistoryService {
    @Autowired
    private ArticleServiceImpl articleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 已经根据参数进行 分页查询
        // 默认按照时间排序降序 desc
        if (StringUtils.isEmpty((String) params.get(Constant.ORDER))) {
            // 排序字段
            params.put(Constant.ORDER_FIELD, "create_time");
            // 排序方式
            params.put(Constant.ORDER, "desc");
        }
        IPage<UserArticleHistoryEntity> page = this.page(
                new Query<UserArticleHistoryEntity>().getPage(params),
                new QueryWrapper<UserArticleHistoryEntity>()
                        .eq("user_id", LoginInterceptor.userIdLocal.get())
        );
        LoginInterceptor.userIdLocal.remove();

       /* List<ArticleDto> collect = page.getRecords().stream().map(entity -> {
            return articleService.getDetailById(entity.getArticleId());
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);*/
        return new PageUtils(page);
    }

    @Override
    public Long getLikesByArticleId(Long articleId) {
        LambdaQueryWrapper<UserArticleHistoryEntity> wrapper = new LambdaQueryWrapper<UserArticleHistoryEntity>()
                .eq(UserArticleHistoryEntity::getUserId, articleId);
        long likes = this.count(wrapper);
        return likes;
    }

}